<?php
if(!defined('IN_ADMINCP')) exit();
define('UPDATE_SERVER', 'http://kkforum.googlecode.com/svn/trunk/');
header('Cache-Control: no-store, no-cache, must-revalidate');
require_once SYSTEM_ROOT.'function/filesock.php';
$step = $_GET['step'];
switch($step){
	case '':
		_index();
		exit();
	case 'welcome':
		_welcome();
		break;
	case 'check_update':
		$data = dfsockopen(UPDATE_SERVER.'hashes.dat?'.TIMESTAMP);
		if(!$data) _output('<p>联网获取数据失败</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?action=updater&step=check_update\');">重试</a>', '系统错误');
		$a = unserialize(pack("H*", $data));
		if(!$a) _output('<p>数据格式不正确，请重试</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?action=updater&step=check_update\');">重试</a>', '系统错误');
		$e = array();
		foreach($a as $f){
			list($p, $h) = explode("\t", $f);
			$c = md5_file(ROOT."./{$p}");
			if($c != $h) $e[] = $p;
		}
		sort($e);
		if(!$e) _output('<p>您当前使用的是最新版本。</p>', '<a class="btn default" href="./">返回论坛</a>', '系统更新');
		_output('<form method="post" action="?action=updater&step=update" id="update" target="loader"><input type="hidden" name="hash" value="'.$formhash.'" /><p>以下文件可以联网更新：</p><p>'.implode('<br>', $e).'</p>', '<a class="btn default" href="javascript:;" onclick="submit_form(\'update\');">开始更新</a>', '系统更新');
		break;
	case 'update':
		if($_POST['hash']!=$formhash) _output('<p>KKBBS 更新程序遇到了一点小问题，请您返回重试。</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?action=updater&step=check_update\');">重试</a>', '系统错误');
		$data = dfsockopen(UPDATE_SERVER.'hashes.dat');
		if(!$data) _output('<p>联网获取数据失败</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?action=updater&step=check_update\');">重试</a>', '系统错误');
		$a = unserialize(pack("H*", $data));
		if(!$a) _output('<p>数据格式不正确，请重试</p>', '<a class="btn default" href="javascript:;" onclick="load_page(\'?action=updater&step=check_update\');">重试</a>', '系统错误');
		$e = array();
		foreach($a as $f){
			list($p, $h) = explode("\t", $f);
			$c = md5_file(ROOT."./{$p}");
			if($c != $h) $e[] = array($p, $h);
		}
		sort($e);
		if(!$e) _output('<p>您当前使用的是最新版本。</p>', '<a class="btn default" href="./">返回论坛</a>', '系统更新');
		foreach($e as $p){
			download_file($p[0], $p[1]);
		}
		_output('<p>已经成功更新到最新版本！</p>', '<a class="btn default" href="./">返回论坛</a>', '更新成功');
	default:
		_output('<p>KKBBS 更新程序遇到了一点小问题，暂时无法继续。</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
}
function download_file($p, $h, $try = 1){
	$c = dfsockopen(UPDATE_SERVER.$p.'?'.TIMESTAMP);
	if(!$c){
		if($try == 3){
			_output('<p>下载文件 '.$p.' 失败，请稍后重试</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
		}else{
			return download_file($p, $h, $try+1);
		}
	}
	if(md5($c) != $h){
		if($try == 3){
			_output('<p>下载文件 '.$p.' 的过程中出现错误，请稍后重试</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
		}else{
			return download_file($p, $h, $try+1);
		}
	}
	if(!file_exists(dirname(ROOT.$p))) dmkdir(dirname(ROOT.$p));
	file_put_contents(ROOT.$p, $c);
	$m = md5_file(ROOT.$p);
	if($m != $h) _output('<p>写入 '.$p.' 的过程中出现错误，请检查文件权限并重试</p>', '<a class="btn default" href="javascript:;" onclick="$(\'loader\').contentWindow.history.back();">返回</a>', '系统错误');
}
function dmkdir($path){
	if(!file_exists(dirname($path))) dmkdir(dirname($path));
	@mkdir($path, 0777);
}
// Templates
function _output($contents, $btns = '', $title = 'KKBBS 安装程序'){
	echo <<<EOF
<div id="content">
<div class="title-bar with-btn">
<a href="javascript:;" class="btn-back" onclick="window.history.back();">Back</a>
<h1>{$title}</h1>
</div>
<div id="main">{$contents}</div>
<div id="btn-bar">{$btns}</div>
</div>
<script>window.parent.callback();</script>
EOF;
	exit();
}
function _welcome(){
	echo <<<EOF
<div id="content">
<div class="title-bar">
<h1>KKBBS 更新程序</h1>
</div>
<div id="main">
<p>欢迎使用 KKBBS 更新程序！</p>
<p>本程序将帮助您更新 KKBBS 至最新版本。</p><br>
<p>请单击“检测更新”按钮开始检查更新</p>
</div>
<div id="btn-bar"><a class="btn default" href="javascript:;" onclick="load_page('?action=updater&step=check_update');">检测更新</a><a class="btn" href="admin.php">返回后台</a></div>
</div>
<script>window.parent.callback();</script>
EOF;
}
function _index(){
	echo <<<EOF
<!DOCTYPE html>
<html>
<head>
<title>KKBBS 更新程序</title>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8">
<meta name="author" content="kookxiang" />
<meta name="copyright" content="KK's Laboratory" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="stylesheet" href="template/default/style/metro.css" type="text/css" />
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<![endif]-->
</head>
<body>
<div id="content">
<div class="title-bar"><h1>KKBBS 更新程序</h1></div>
<div id="main"></div><div id="btn-bar"></div></div>
<div id="load-win">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="50" height="50"><param name="movie" value="template/default/style/loading.swf"><param name="quality" value="high"><param name="wmode" value="transparent"><embed src="template/default/style/loading.swf" quality="high" wmode="transparent" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="50" height="50"></embed></object>
</div>
<iframe id="loader" onload="callback()"></iframe>
<script>
var content = '';
var is_ie = false;
if(document.all) is_ie = true;
function $(id){
	return document.getElementById(id);
}
function load_win(status){
	$('load-win').className = status ? 'show' : 'hide';
	$('main').style.display = status ? 'none' : '';
	$('btn-bar').style.display = status ? 'none' : '';
}
function load_page(url){
	load_win(true);
	$('loader').src = url;
}
function submit_form(formid){
	load_win(true);
	$(formid).target = 'loader';
	$(formid).submit();
}
function callback(){
	try{
		if(is_ie){
			content = document.frames['loader'].document.getElementById('content').innerHTML;
		}else{
			content = $('loader').contentDocument.getElementById('content').innerHTML;
		}
	}catch(e){
		alert('无法加载页面，请稍后重试！');
		load_win(false);
		return;
	}
	$('content').innerHTML = content;
	load_win(false);
}
load_page('?action=updater&step=welcome');
</script>
</body>
</html>
EOF;
}
